/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.webapp.security;

import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
import org.jrose.core.util.AESUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.Map;

public class SecurityCookieManager {
    private static final String PREFIX = "ENCRYPTED:";

    @NonNull private final HttpServletResponse response;
    private final Map<String, Cookie> cookies;

    public SecurityCookieManager(HttpServletRequest request, HttpServletResponse response) {
        this.response = response;
        this.cookies = new LinkedHashMap<>();

        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                this.cookies.put(cookie.getName(), cookie);
            }
        }
    }

    public void setSecurityCookie(String name, String value, int expiry) {
        value = AESUtils.encryptAsBase64(value);
        value = PREFIX + value;
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(expiry);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    public String getCookie(String cookieName) {
        if (!cookies.containsKey(cookieName)) {
            return null;
        }
        Cookie cookie = cookies.get(cookieName);
        String value = cookie.getValue();
        if (StringUtils.startsWith(value, PREFIX)) {
            value = StringUtils.substringAfter(value, PREFIX);
            value = AESUtils.decryptFromBase64(value);
        }
        return value;
    }
}
